package com.linwen.excise.leetcode;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author : linwen
 * @date : 下午6:30 2021/4/4
 */
public class _350两个数组的交集II {
    public static void main(String[] args) {
        int[] arr2 = new int[]{4,9,5};
        int[] arr1 = new int[]{9,4,9,8,4};
        int[] intersect = _350两个数组的交集II.intersect(arr1, arr2);
        for (int i : intersect) {
            System.out.print(i+"  ");
        }

    }
    public static int[] intersect(int[] nums1, int[] nums2) {
        if(nums1.length<nums2.length){
            return intersect(nums2,nums1);
        }
        ArrayList<Integer> result = new ArrayList<Integer>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int n = 0 , m = 0;
        while (true){
            if(n>nums1.length-1 || m>nums2.length-1){
                break;
            }
            if(nums1[n]==nums2[m]){
                result.add(nums2[m]);
                n++;
                m++;
            }else if(nums1[n]<nums2[m]){
                n++;
            }else if(nums1[n]>nums2[m]){
                m++;
            }
        }
        return result.stream().mapToInt(Integer::valueOf).toArray();
    }
}
